import { useState, useEffect, useRef } from 'react'
import { Card, Breadcrumb, Form, Button, Radio, Input, Upload, Space, Select, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { http } from '@/utils'
import './index.scss'

const { Option } = Select

function Publish() {
  // 编辑初始化
  const [form] = Form.useForm()
  const [params] = useSearchParams()
  const articleId = params.get('id')
  useEffect(() => {
    // 数据回显
    async function getArticle(id) {
      const { data } = await http.get(`/api/article/detail?id=${id}`)
      if (data) {
        const { title, type, content, cover, channel } = data
        form.setFieldsValue({ title, type, content, channel })
        if (cover.images && cover.images.length) {
          const imagesList = cover.images.map(item => {
            return { url: item }
          })
          setFileList(imagesList)
          fileListRef.current = imagesList
          setMaxCount(type)
        }
      }
    }
    if (articleId) {
      getArticle(articleId)
    }
  }, [articleId, form])

  // 图片暂存仓库
  const fileListRef = useRef([])
  // 主题管理
  const [channels, setChannels] = useState([])
  useEffect(() => {
    (async function() {
      const { data } = await http.get('/api/article/channels')
      if (data) {
        setChannels(data)
      }
    })()
  }, [])

  // 上传文件管理
  const [fileList, setFileList ] = useState([])
  const onUploadChange = info => {
    const fileList = info.fileList.map(file => {
      if (file.response) {
        return {
          url: file.response.data.url
        }
      }
      return file
    })
    setFileList(fileList)
    // 暂存图片
    fileListRef.current = fileList
  }

  // 最大上传量管理
  const [maxCount, setMaxCount] = useState(1)
  const changeType = e => {
    const count = e.target.value
    setMaxCount(count)
    if (count === 1) {
      const firstImg = fileListRef.current[0] || null
      setFileList(firstImg ? [firstImg] : [])
    } else if (count === 3) {
      setFileList(fileListRef.current)
    } else {
      setFileList([])
    }
  }

  // 发布
  const navigate = useNavigate()
  const onSubmit = async (values) => {
    console.log('values', values)
    const { title, type, content, channel } = values
    const params = {
      title,
      type,
      content,
      channel,
      cover: {
        images: fileList.map(item => item.url)
      }
    }
    let pubPath = '/api/article/publish'
    if (articleId) {
      pubPath = `/api/article/publish?id={articleId}`
    }
    const { data } = await http.post(pubPath, params)
    if (data) {
      message.success('发布成功')
      navigate('/article')
    }
  }

  return (
    <div className='publish'>
      <Card 
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {articleId ? '编辑文章' : '发布文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1, content: '' }}
          onFinish={onSubmit}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              { required: true, message: '请输入文章标题'}
            ]}
          >
            <Input placeholder='请输入文章标题' style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="主题"
            name="channel"
            rules={[
              { required: true, message: '请选择文章主题'}
            ]}
          >
            <Select placeholder='请选择文章主题' style={{ width: 400 }}>
              {
                channels.length && channels.map(channel =>
                  <Option value={channel.value} key={channel.id}>{channel.label}</Option>
                )
              }
            </Select>
          </Form.Item>
          <Form.Item
            label="封面"
            name="type"
          >
            <Radio.Group onChange={changeType}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="选择封面">
            <Upload
              name='image'
              listType='picture-card'
              className='avatar-upload'
              showUploadList
              action="http://geek.itheima.net/v1_0/upload"
              fileList={fileList}
              maxCount={maxCount}
              multiple={ maxCount > 1 }
              onChange={onUploadChange}
            >
              <div style={{ marginTop: 8 }}>
                <PlusOutlined />
              </div>
            </Upload>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[
              { required: true, message: "请输入文章内容" }
            ]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>
          <Form.Item>
            <Space style={{ marginLeft: '16.6%' }}>
              <Button size='large' type='primary' htmlType='submit'>发布文章</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish